import store from '../store';
import {
	toLogin
} from './login.js';

const TOKENNAME = 'Authori-zation';
let header = {
	'content-type': 'application/json',
	//#ifdef H5
	'Form-type': navigator.userAgent.toLowerCase().indexOf("micromessenger") !== -1 ? 'wechat' : 'h5',
	//#endif
	//#ifdef MP
	'Form-type': 'routine',
	//#endif
	//#ifdef APP-VUE
	'Form-type': 'app',
	//#endif
}

function baseRequest(api, method, data, opts = {
	noAuth: false
}) {
	if (opts.noAuth) {
		console.log("---123：",store.state.app.token);
		if(!store.state.app.token){
			toLogin();
		}
	}

	if (uni.getStorageSync('token')) {
		let token = uni.getStorageSync('token')
		header[TOKENNAME] = 'Bearer ' + token;
	}
	if (store.state.app.token) header[TOKENNAME] = 'Bearer ' + store.state.app.token;
	return new Promise((reslove, reject) => {
		uni.request({
			url: api,
			method: method || 'GET',
			header: header,
			data: data || {},
			success: (res) => {
				if (res.data.status == 200)
					console.log("res..", res);
				reslove(res);
			},
			fail: (msg) => {
				reject('请求失败');
			}
		})
	});
}




const request = {};
const methods = ['options', 'get', 'post', 'put', 'head', 'delete', 'trace', 'connect'];
methods.forEach(method => {
	request[method] = (api, data, opts) => baseRequest(api, method, data,opts);
})

export default request;
